<?php
namespace Lib;

final class Wechat {
    use \Lib\Traits\Instance;

    public function getToken() {
        $redis = \Yaf\Registry::get('redis');
        $token = $redis->get('wx.access_token');

        if(empty($token)) {
            $token = $this->setToken();
        }

        return $token;
    }

    public function setToken() {
        $token = $this->getAccessToken();

        $beginTime = time();

        while(empty($token) && (time() - $beginTime < 59)) {
            $token = $this->getAccessToken();
        }

        if(empty($token)) {
            throw new \exception('获取access_token失败！');
        }

        $redis = \Yaf\Registry::get('redis');
        $redis->set('wx.access_token', $token);
        $redis->expire('wx.access_token', \Lib\Consts::EXPIRE_2HOUR - 60);

        return $token;
    }

    protected function getAccessToken() {
        $params['appid']      = \Lib\Pay\WxPayConfig::appid();
        $params['secret']     = \Lib\Pay\WxPayConfig::appsecret();
        $params['grant_type'] = 'client_credential';

        try {
            $http = new \Lib\Http();
            $http->setPostFields($params);
            $http->setUrl('https://api.weixin.qq.com/cgi-bin/token');
            $http->setTimeout(30);
            $returnMsg = json_decode($http->send());
        } catch(\Exception $exc) {
            $msg['status'] = false;
            $returnMsg     = new \Lib\Std($msg);
        }
//var_dump($returnMsg, property_exists($returnMsg, 'access_token') ? $returnMsg->access_token : '');die('123');
        return property_exists($returnMsg, 'access_token') ? $returnMsg->access_token : '';
    }

    public function oauth() {
        $request = \Yaf\Dispatcher::getInstance()->getRequest();
        $code    = (string)$request->get('code');

        $params['appid']      = \Lib\Pay\WxPayConfig::appid();
        $params['secret']     = \Lib\Pay\WxPayConfig::appsecret();
        $params['code']       = $code;
        $params['grant_type'] = 'authorization_code';

        try {
            $http = new \Lib\Http();
            $http->setPostFields($params);
            $http->setUrl('https://api.weixin.qq.com/sns/oauth2/access_token');
            $http->setTimeout(3);
            $returnMsg = json_decode($http->send());
        } catch(\Exception $exc) {
            $msg['status'] = false;
            $returnMsg     = new \Lib\Std($msg);
        }

        return $returnMsg;
    }

    public function user($openId, $accessToken) {
        $params['access_token'] = $accessToken;
        $params['openid']       = $openId;
        $params['lang']         = 'zh_CN';
        $params['grant_type']   = 'authorization_code';

        try {
            $http = new \Lib\Http();
            $http->setPostFields($params);
            $http->setUrl('https://api.weixin.qq.com/sns/userinfo');
            $http->setTimeout(3);
            $returnMsg = json_decode($http->send());
        } catch(\Exception $exc) {
            $msg['status'] = false;
            $returnMsg     = new \Lib\Std($msg);
        }

        return $returnMsg;
    }

    public function login() {
        $url  = 'http://api.dev.gaoqiapp.com/wx/member/oauth';
        $host = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . \Lib\Pay\WxPayConfig::appid() . "&redirect_uri=" . $url . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        return $host;
    }

    public function doSend($touser, $templateId, $url, $data, $topColor = '#7B68EE') {
        if($templateId === \Lib\Consts::TEMP_ID_PAY_BUY) {
            if(!array_key_exists('nickname', $data) || !array_key_exists('time_interval', $data)) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '您已成功抱大腿~'],
                'keyword1' => ['value' => $data['nickname']],
                'keyword2' => ['value' => $data['time_interval']],
                'remark'   => ['value' => '为了抱好大腿，请提前安排好时间~'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_PAY_SELL) {
            if(!array_key_exists('nickname', $data) || !array_key_exists('time_interval', $data)
                || !array_key_exists('date', $data) || !array_key_exists('price', $data)
            ) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '有人预约您的大腿啦~'],
                'keyword1' => ['value' => $data['date']],
                'keyword2' => ['value' => $data['time_interval']],
                'keyword3' => ['value' => $data['nickname']],
                'keyword4' => ['value' => $data['tel']],
                'keyword5' => ['value' => $data['price'] . '元'],
                'remark'   => ['value' => '请提早准备哦~'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_REFUND) {
            if(!array_key_exists('order_no', $data) || !array_key_exists('time', $data)
                || !array_key_exists('cancel_time', $data) || !array_key_exists('price', $data)
            ) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '啊哦，大腿已取消您的订单~'],
                'keyword1' => ['value' => $data['order_no']],
                'keyword2' => ['value' => $data['time']],
                'keyword3' => ['value' => $data['cancel_time']],
                'keyword4' => ['value' => $data['price'] . '元'],
                'remark'   => ['value' => '如有任何疑问，请直接咨询搞起在线客服~'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_FINISH_BUY) {
            if(!array_key_exists('nickname', $data) || !array_key_exists('price', $data)) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '尊敬的用户，您的抱大腿完成啦~'],
                'keyword1' => ['value' => $data['nickname']],
                'keyword2' => ['value' => $data['price'] . '元'],
                'remark'   => ['value' => '么么哒~期待您再次的翻牌子哟!'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_FINISH_SELL) {
            if(!array_key_exists('nickname', $data) || !array_key_exists('mobile', $data)) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '您的小弟确认完成啦~他支付的钱将会打入您的搞起余额'],
                'keyword1' => ['value' => $data['nickname']],
                'keyword2' => ['value' => $data['nickname']],
                'keyword3' => ['value' => $data['mobile']],
                'remark'   => ['value' => '收到钱啦，快去再发布个新大腿消息吧~'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_NO_PAY) {
            if(!array_key_exists('order_no', $data) || !array_key_exists('add_time', $data)) {
                return false;
            }

            $tmpData = [
                'first'     => ['value' => '有客户下单购买您的时间咯~'],
                'ordertape' => ['value' => $data['add_time']],
                'ordeID'    => ['value' => '【' . $data['order_no'] . '】'],
                'remark'    => ['value' => '如果几分钟内ta还未付款，可进入搞起详情直接拨打电话提醒对方付款哦~'],
            ];
        }

        if(empty($tmpData)) {
            return false;
        }

        $params['touser']      = $touser;
        $params['template_id'] = $templateId;
        $params['url']         = $url;
        $params['topcolor']    = $topColor;
        $params['data']        = $tmpData;

        try {
            $http = new \Lib\Http();
            $http->setPostFields(json_encode($params));
            $http->setUrl("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $this->getAccessToken());
            $http->setTimeout(3);
            $returnMsg = json_decode($http->send());
        } catch(\Exception $exc) {
            $msg['status'] = false;
            $returnMsg     = new \Lib\Std($msg);
        }

        return $returnMsg;
    }

    public function getTmp($templateId, $data) {
        $tmpData = [];

        if($templateId === \Lib\Consts::TEMP_ID_PAY_BUY) {
            if(!array_key_exists('nickname', $data) || !array_key_exists('time_interval', $data)) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '您已成功抱大腿~'],
                'keyword1' => ['value' => $data['nickname']],
                'keyword2' => ['value' => $data['time_interval']],
                'remark'   => ['value' => '为了抱好大腿，请提前安排好时间~'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_PAY_SELL) {
            if(!array_key_exists('nickname', $data) || !array_key_exists('time_interval', $data)
                || !array_key_exists('date', $data) || !array_key_exists('price', $data)
            ) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '有人预约您的大腿啦~'],
                'keyword1' => ['value' => $data['date']],
                'keyword2' => ['value' => $data['time_interval']],
                'keyword3' => ['value' => $data['nickname']],
                'keyword4' => ['value' => $data['tel']],
                'keyword5' => ['value' => $data['price'] . '元'],
                'remark'   => ['value' => '请提早准备哦~'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_REFUND) {
            if(!array_key_exists('order_no', $data) || !array_key_exists('time', $data)
                || !array_key_exists('cancel_time', $data) || !array_key_exists('price', $data)
            ) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '啊哦，大腿已取消您的订单~'],
                'keyword1' => ['value' => $data['order_no']],
                'keyword2' => ['value' => $data['time']],
                'keyword3' => ['value' => $data['cancel_time']],
                'keyword4' => ['value' => $data['price'] . '元'],
                'remark'   => ['value' => '如有任何疑问，请直接咨询搞起在线客服~'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_FINISH_BUY) {
            if(!array_key_exists('nickname', $data) || !array_key_exists('price', $data)) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '尊敬的用户，您的抱大腿完成啦~'],
                'keyword1' => ['value' => $data['nickname']],
                'keyword2' => ['value' => $data['price'] . '元'],
                'remark'   => ['value' => '么么哒~期待您再次的翻牌子哟!'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_FINISH_SELL) {
            if(!array_key_exists('nickname', $data) || !array_key_exists('mobile', $data)) {
                return false;
            }

            $tmpData = [
                'first'    => ['value' => '您的小弟确认完成啦~他支付的钱将会打入您的搞起余额'],
                'keyword1' => ['value' => $data['nickname']],
                'keyword2' => ['value' => $data['nickname']],
                'keyword3' => ['value' => $data['mobile']],
                'remark'   => ['value' => '收到钱啦，快去再发布个新大腿消息吧~'],
            ];
        } elseif($templateId === \Lib\Consts::TEMP_ID_NO_PAY) {
            if(!array_key_exists('order_no', $data) || !array_key_exists('add_time', $data)) {
                return false;
            }

            $tmpData = [
                'first'     => ['value' => '有客户下单购买您的时间咯~'],
                'ordertape' => ['value' => $data['add_time']],
                'ordeID'    => ['value' => '【' . $data['order_no'] . '】'],
                'remark'    => ['value' => '如果几分钟内ta还未付款，可进入搞起详情直接拨打电话提醒对方付款哦~'],
            ];
        }

        return $tmpData;
    }

}
